package de.suur.jarmi.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import de.suur.jarmi.common.Response;

/**
 * @author Martin Nonnenmacher
 */
public class JarmiSocketServer extends Thread {

	private boolean cancel;
	private final int port;
	private RequestHandler requestHandler;

	public JarmiSocketServer(int port) {
		cancel = false;
		this.port = port;
	}

	public RequestHandler getRequestHandler() {
		return requestHandler;
	}

	@Override
	public void run() {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);
			serverSocket.setSoTimeout(1000);
			while (!cancel) {
				try {
					final Socket socket = serverSocket.accept();
					new Thread() {
						@Override
						public void run() {
							try {
								Response response = requestHandler
										.handle(socket.getInputStream());
								byte[] responseData = requestHandler
										.serialize(response);
								responseData = requestHandler
										.compress(responseData);
								requestHandler.writeResponse(socket
										.getOutputStream(), responseData);
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}.start();
				} catch (SocketTimeoutException e) {
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			serverSocket.close();
		} catch (IOException e1) {
			e1.printStackTrace();
			if (serverSocket != null && !serverSocket.isClosed()) {
				try {
					serverSocket.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
		}

	}

	public void setRequestHandler(RequestHandler requestHandler) {
		this.requestHandler = requestHandler;
	}

	public void shutdown() {
		cancel = true;
	}

}
